﻿<%@ Page Language="C#" AutoEventWireup="true" CodeFile="adduser.aspx.cs" Inherits="MovieTixStaff_adduser" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    public void function1(object source, ServerValidateEventArgs args)
    {

        string username = UsernameTextbox.Text;
        Label2.Text = "1";

        string connectionString;
        connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd1 = new SqlCommand("SELECT TheatreStaffUserName,TheatreId from TheatreStaff WHERE TheatreStaffUserName=@TheatreStaffUserName", con);
     
        Boolean Showing;

        cmd1.Parameters.AddWithValue("TheatreStaffUserName", username);
        using (con)
        {
            con.Open();
            SqlDataReader reader = cmd1.ExecuteReader();
            if (reader.HasRows)
            {
                Label2.Text = "1";
                args.IsValid = false;
                Showing = false;


            }
            else
            {
                Label2.Text = "2";
                Showing = true;
                args.IsValid = true;
            }
        }
    }
    public void Clear(object sender, EventArgs args)
    {
        Label1.Text = " ";


    }
    //protected void test(object sender, EventArgs e)
    //{


        //string connectionString;
        //connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        //SqlConnection con = new SqlConnection(connectionString);
        //SqlConnection con1 = new SqlConnection(connectionString);
        //SqlCommand cmd1 = new SqlCommand("INSERT TheatreStaff (TheatreStaffUserName,TheatreId) values (@TheatreStaffUserName,@TheatreId)", con1);

        //Boolean Showing;
        //Int32 RowCount;
        //Boolean HasMovies;

        //cmd1.Parameters.AddWithValue("@TheatreStaffUserName", CreateUserWizard1.UserName);

        //cmd1.Parameters.AddWithValue("@TheatreId", theatre2.SelectedValue);


        //using (con1)
        //{
        //    con1.Open();
        //    cmd1.Parameters.AddWithValue("@TheatreStaffUserName", CreateUserWizard1.UserName);

        //    cmd1.Parameters.AddWithValue("@TheatreId", theatre2.SelectedValue);


        //}

        //SqlDataSource1.InsertParameters["TheatreStaffUserName"].DefaultValue = CreateUserWizard1.UserName;
        //SqlDataSource1.InsertParameters["TheatreID"].DefaultValue = theatre2.SelectedItem.Value;
        //Label4.Text = CreateUserWizard1.UserName;
        //Label2.Text = theatre2.SelectedItem.Value;
        //SqlDataSource1.Insert();
        //theatre2.Visible = false;
        //Label3.Visible = false;
        //string staff = CreateUserWizard1.UserName;
        //Roles.AddUserToRole(staff, "Theatre");
        //Roles.AddUserToRole(staff, "TheatreAdmin");

    //}




    public void CreateUser_OnClick(object sender, EventArgs args)
    {

        string username = UsernameTextbox.Text;
        Label2.Text = "1";

        string connectionString1;
        connectionString1 = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection con1 = new SqlConnection(connectionString1);
        SqlCommand cmd1 = new SqlCommand("SELECT TheatreStaffUserName,TheatreId from TheatreStaff WHERE TheatreStaffUserName=@TheatreStaffUserName", con1);
     
        Boolean Showing;

        cmd1.Parameters.AddWithValue("TheatreStaffUserName", username);
        using (con1)
        {
            con1.Open();
            SqlDataReader reader = cmd1.ExecuteReader();
            if (reader.HasRows)
            {
                Label2.Text = "1";

                Showing = false;


            }
            else
            {
                Label2.Text = "2";
                Showing = true;

            }
        }


        if (Showing == true)
        {
          

            MembershipCreateStatus result;

            try
            {
                // Create new user.

                if (Membership.RequiresQuestionAndAnswer)
                {
                    MembershipUser newUser = Membership.CreateUser(
                      UsernameTextbox.Text,
                      PasswordTextbox.Text,
                      EmailTextbox.Text,
                      PasswordQuestionTextbox.Text,
                      PasswordAnswerTextbox.Text,
                      true,
                      out result);


                    if (Roles.RoleExists("Theatreadmin"))
                    {
                      
                        if (!Roles.IsUserInRole(UsernameTextbox.Text, "Theatreadmin"))
                        {

                            Roles.AddUserToRole(UsernameTextbox.Text, "Theatreadmin");
                        }
                    }
                    string connectionString;
                    connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

                    SqlConnection con = new SqlConnection(connectionString);
                    SqlCommand cmd = new SqlCommand("INSERT TheatreStaff(TheatreStaffUserName,TheatreStaffAcessLevel,TheatreId) values (@UName,@ALevel,@Id)", con);
                    cmd.Parameters.AddWithValue("@UName", UsernameTextbox.Text);
                    cmd.Parameters.AddWithValue("@ALevel", "Admin");
                    cmd.Parameters.AddWithValue("@Id", theatre2.SelectedItem.Value);
                       
                    Label1.Text = "The New user has been added sucessfully to the theatre!";
                    
                    using (con)
                    {
                        con.Open();
                        Int32 rowCount = cmd.ExecuteNonQuery();

                        if (rowCount > 0)
                        {
                            Label1.Text = "The New user [" + UsernameTextbox.Text + "] has been added sucessfully to the theatre " + theatre2.SelectedItem.Text;
                    
                            UsernameTextbox.Text = "";
                            PasswordTextbox.Text = "";
                            EmailTextbox.Text = "";
                            PasswordQuestionTextbox.Text = "";
                            PasswordAnswerTextbox.Text = "";
                         
                          
                          
                        }

                    }
                }
                else
                {
                    MembershipUser newUser = Membership.CreateUser(
                      UsernameTextbox.Text,
                      PasswordTextbox.Text,
                      EmailTextbox.Text);
                    if (Roles.RoleExists("Theatreadmin"))
                    {
                  
                        if (!Roles.IsUserInRole(UsernameTextbox.Text, "Theatreadmin"))
                        {

                            Roles.AddUserToRole(UsernameTextbox.Text, "Theatreadmin");
                        }
                    }
                    string connectionString;
                    connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

                    SqlConnection con = new SqlConnection(connectionString);
                    SqlCommand cmd = new SqlCommand("INSERT TheatreStaff(TheatreStaffUserName,TheatreStaffAcessLevel,TheatreId) values (@UName,@ALevel,@Id)", con);
                    cmd.Parameters.AddWithValue("@UName", UsernameTextbox.Text);
                    cmd.Parameters.AddWithValue("@ALevel", "Admin");
                    cmd.Parameters.AddWithValue("@Id", theatre2.SelectedItem.Value);
                       

                    using (con)
                    {
                        con.Open();
                        Int32 rowCount = cmd.ExecuteNonQuery();

                        //if (rowCount > 0)
                        //{
                        //    lresult.Text = "The New user has been added sucessfully to the theatre!";
                        //}

                    }
                }

                //Response.Redirect("login.aspx");
            }
            catch (MembershipCreateUserException e)
            {
                Msg.Text = GetErrorMessage(e.StatusCode);
            }
            catch (HttpException e)
            {
                Msg.Text = e.Message;
            }

        }
    }

    public string GetErrorMessage(MembershipCreateStatus status)
    {
        switch (status)
        {
            case MembershipCreateStatus.DuplicateUserName:
                return "Username already exists. Please enter a different user name.";

            case MembershipCreateStatus.DuplicateEmail:
                return "A username for that e-mail address already exists. Please enter a different e-mail address.";

            case MembershipCreateStatus.InvalidPassword:
                return "The password provided is invalid. Please enter a valid password value.";

            case MembershipCreateStatus.InvalidEmail:
                return "The e-mail address provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidAnswer:
                return "The password retrieval answer provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidQuestion:
                return "The password retrieval question provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidUserName:
                return "The user name provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.ProviderError:
                return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

            case MembershipCreateStatus.UserRejected:
                return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

            default:
                return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
        }
    }
</script>
</script>
<%--This below code from the website:http://ramanisandeep.wordpress.com/2008/11/07/hide-an-aspnet-label-control-after-a-few-seconds/--%>
<script type="text/javascript">
    self.setInterval("changeValue()", 5000);

    function changeValue() {
        document.getElementById("Label1").innerText = "";

    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<style type="text/css">
html
{
    background-color:Black;
    color:White;
    padding-left:40px;
}
</style>
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <asp:Label ID="lblId" runat="server" Visible="false" ></asp:Label>
   <asp:UpdatePanel ID="UpdatePanel1" runat="server">
             <ContentTemplate>
 
      <asp:Label id="Msg" ForeColor="maroon" runat="server" />
      
         
       <asp:Label ID="Label1"   runat="server" Font-Bold="True" Font-Size="Larger"  
            ForeColor="#FFFFCC"></asp:Label>   <br />
         
    <asp:Label ID="Label6" runat="server" Text="Please complete the following form: " Font-Bold="True" Font-Size="Large" ForeColor="#CCFFFF"></asp:Label><br />
        <br />
        <asp:Label ID="Label4" runat="server" Text="" Visible="false"></asp:Label>
            <asp:Label ID="Label2" runat="server" Text="" Visible="false"></asp:Label>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
   

 <asp:UpdatePanel ID="UpdatePanel2"   runat="server">
        <ContentTemplate>
    
         
      <table>  
     <tr><td><asp:Label ID="Label3" runat="server" Text="Please select a theatre"></asp:Label> </td>      
<td>
  
<asp:DropDownList id="theatre2"     DataSourceID="theatre" DataTextField="theatrename"   DataValueField="Theatreid" runat="server" >
</asp:DropDownList>


       
 <asp:SqlDataSource id="theatre" runat="server" 
                ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
                SelectCommand="SELECT  [TheatreId], [TheatreName] FROM [Theatre]" />
               
                
                 </td></tr>
            </table>           
    </ContentTemplate></asp:UpdatePanel>   
      <%--  <asp:CreateUserWizard ID="CreateUserWizard1" OnCreatedUser="test"   UserNameRequiredErrorMessage="Required"   InstructionText="Please complete the following form:"  ContinueDestinationPageUrl="~/MovieTixStaff/AddTheatre.aspx"     LoginCreatedUser="false"   runat="server">
     <WizardSteps>
                <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server">
             <ContentTemplate>
      
        <table align="left" width="400px">  


<tr><td >     <asp:Label id="lblUserName" Text="User Name:" AssociatedControlID="UserName" Runat="server" /></td>

<td>   <asp:TextBox  id="UserName" Runat="server" />

</td><asp:RequiredFieldValidator ID="Required2" ControlToValidate="UserName"
    runat="server" ErrorMessage="Required"/></tr>

   <tr><td><asp:Label id="lblPassword" Text="Password:" AssociatedControlID="Password" Runat="server" /></td>

 <td>  <asp:TextBox id="Password" TextMode="Password" Runat="server" /><asp:RequiredFieldValidator ID="Required3" ControlToValidate="Password"
    runat="server" ErrorMessage="Required"/></td></tr>
<tr><td>
 <asp:Label id="lblEmail" Text="Email:" AssociatedControlID="Email" Runat="server" /></td>
<td>   <asp:TextBox id="Email" Runat="server" /><asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="Email"
    runat="server" ErrorMessage="Required"/></td></tr>

<tr><td> <asp:Label id="lblQuestion" Text="Security Question:"  AssociatedControlID="Question" Runat="server" /></td>
<td><asp:DropDownList id="Question" Runat="server">
      <asp:ListItem  Text="Enter the name of your pet" Value="Pet Name" />
<asp:ListItem  Text="Enter your favorite color" Value="Favorite Color" />
        </asp:DropDownList></td></tr> 

<tr><td> <asp:Label id="lblAnswer" Text="Security Answer:" AssociatedControlID="Answer" Runat="server" /></td>

    <td>    <asp:TextBox id="Answer"  Runat="server" /><asp:RequiredFieldValidator ID="RequiredFieldValidator3" ControlToValidate="Answer"
    runat="server" ErrorMessage="Required"/></td></tr>          
          
    </table>  
            

               </ContentTemplate>

               </asp:CreateUserWizardStep>
               
               <asp:CompleteWizardStep>
               <ContentTemplate>
               The Account is created successfully<br />
                   <asp:Button ID="Button1" runat="server"  PostBackUrl="~/MovieTixStaff/adduser.aspx" Text="Button" />
               
             </ContentTemplate>
               </asp:CompleteWizardStep>
      </WizardSteps>
        </asp:CreateUserWizard>--%>
 


  <table cellpadding="3" border="0">
    <tr>
      <td>Username:</td>
      <td><asp:Textbox  id="UsernameTextbox" OnTextChanged="Clear"   runat="server" /></td>
      <td><asp:RequiredFieldValidator id="UsernameRequiredValidator" runat="server"
                                      ControlToValidate="UserNameTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" />
    <asp:CustomValidator  ID="CustomValidator1"  ControlToValidate="UsernameTextbox"  OnServerValidate="function1"  runat="server" Text="This username already exist, please try another" ErrorMessage="CustomValidator" />                         
                                      
                                      
                                      
                                      </td>
    </tr>
    <tr>
      <td>Password:</td>
      <td><asp:Textbox id="PasswordTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="PasswordRequiredValidator" runat="server"
                                      ControlToValidate="PasswordTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Confirm Password:</td>
      <td><asp:Textbox id="PasswordConfirmTextbox" runat="server" TextMode="Password" /></td>
      <td><asp:RequiredFieldValidator id="PasswordConfirmRequiredValidator" runat="server"
                                      ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" />
          <asp:CompareValidator id="PasswordConfirmCompareValidator" runat="server"
                                      ControlToValidate="PasswordConfirmTextbox" ForeColor="red"
                                      Display="Static" ControlToCompare="PasswordTextBox"
                                      ErrorMessage="Confirm password must match password." />
      </td>
    </tr>
    <tr>
      <td>Email Address:</td>
      <td><asp:Textbox id="EmailTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="EmailRequiredValidator" runat="server"
                                      ControlToValidate="EmailTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>


<% if (Membership.RequiresQuestionAndAnswer) { %>

    <tr>
      <td>Password Question:</td>
      <td><asp:Textbox id="PasswordQuestionTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="PasswordQuestionRequiredValidator" runat="server"
                                      ControlToValidate="PasswordQuestionTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>
    <tr>
      <td>Password Answer:</td>
      <td><asp:Textbox id="PasswordAnswerTextbox" runat="server" /></td>
      <td><asp:RequiredFieldValidator id="PasswordAnswerRequiredValidator" runat="server"
                                      ControlToValidate="PasswordAnswerTextbox" ForeColor="red"
                                      Display="Static" ErrorMessage="Required" /></td>
    </tr>

<% } %>


    <tr>
      <td></td>
      <td><asp:Button id="CreateUserButton" Text="Create User" OnClick="CreateUser_OnClick" runat="server" /></td>
    </tr>
    
  </table>
  </ContentTemplate>
             </asp:UpdatePanel>



















        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
            ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
            
            InsertCommand="INSERT INTO [TheatreStaff] ([TheatreStaffUserName], [TheatreId]) VALUES (@TheatreStaffUserName, @TheatreId)"  >

            <InsertParameters>
                <asp:Parameter Name="TheatreStaffUserName" Type="String" />
                <asp:Parameter Name="TheatreId" Type="Int16" />
            </InsertParameters>
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>
